package com.jrx.anytxn.transaction.job.paph.config;

import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.service.IPaphFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 生成平安普惠回传的文件
 *
 * @author liuyang
 * @date 2021-3-17
 */
@Configuration
@EnableConfigurationProperties(PaphFileConfig.class)
public class GenerateImageFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateImageFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IPaphFileService paphFileService;

    @Autowired
    private PaphFileConfig paphFileConfig;

    @Bean
    public Job generateImageFileJob() {
        return jobBuilderFactory.get("generateImageFileJob")
                .start(preterminationFileStep())
                .next(contractFileStep())
                .build();
    }

    @Bean
    public Step preterminationFileStep() {
        return stepBuilderFactory.get("preterminationFileStep")
                .tasklet(preterminationFileTasklet())
                .build();
    }

    @Bean
    public Step contractFileStep() {
        return stepBuilderFactory.get("contractFileStep")
                .tasklet(contractFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet preterminationFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("=====平安普惠提前结清证明文件处理开始=====");
            paphFileService.disposePreterminationFile(paphFileConfig.getBackImagePath(), paphFileConfig.getBackImageFromPath());
            logger.info("=====平安普惠提前结清证明文件处理完成=====");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    @StepScope
    public Tasklet contractFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("=====平安普惠借款合同处理开始=====");
            paphFileService.disposeContractFile(paphFileConfig.getBackImagePath(), paphFileConfig.getBackLoanFromPath());
            logger.info("=====平安普惠借款合同处理完成=====");
            return RepeatStatus.FINISHED;
        };
    }
}
